package operation;

import entity.text.ChapterEntity;
import entity.text.LancetPaperEntity;
import entity.text.PaperEntity;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.tree.DefaultAttribute;
import org.dom4j.tree.DefaultElement;
import util.CollectionUtils;
import util.SplitTextInSentence;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringJoiner;

/**
 * @author ：hzs
 * @date ：Created in 2021/4/5 22:40
 * @description：
 * @modified By：
 * @version: $
 */
public class LancetXmlFileOperation extends AbstractFileOperation {

    @Override
    public String loadTextFromFile(File file) {
        return null;
    }

    @Override
    public PaperEntity getPaperEntityFromFile(File file) throws Exception {
        String fileName = file.getName();
        if (!fileName.endsWith(".xml") && !fileName.endsWith(".XML")) {
            throw new Exception("文件类型错误，不是xml文件");
        }
        Document document = new SAXReader().read(file);
        Element rootElement = document.getRootElement();
        LancetPaperEntity paperInformationFromFile = new LancetPaperEntity();

        String url = rootElement.elementText("url");
        String publicationDate = rootElement.elementText("publicationDate");
        String title = rootElement.elementText("title");
        String authors = rootElement.elementText("authors");
        Element content = rootElement.element("content");

        List<ChapterEntity> chapterEntities = new ArrayList<>();
        for (Object element : content.elements()) {
            String subTitle = ((DefaultElement) element).elementText("title");
            if ("Summary".equals(subTitle)) {
                List<DefaultElement> elements = ((DefaultElement) element).elements("section");
                elements = elements.get(0).elements();
                for (int i = 0; i < elements.size(); i++) {
                    DefaultElement defaultElement = elements.get(i);
                    if ("sectionTitle".equals(defaultElement.getName())) {
                        String text = defaultElement.getText();
                        switch (text) {
                            case "Background":
                                paperInformationFromFile.setBackgroud(elements.get(++i).getText());
                                break;
                            case "Methods":
                                paperInformationFromFile.setMethods(elements.get(++i).getText());
                                break;
                            case "Findings":
                                paperInformationFromFile.setFindings(elements.get(++i).getText());
                                break;
                            case "Interpretation":
                                paperInformationFromFile.setInterpretation(elements.get(++i).getText());
                                break;
                            case "Funding":
                                paperInformationFromFile.setFunding(elements.get(++i).getText());
                                break;
                            default:
                                paperInformationFromFile.setOther(paperInformationFromFile.getOther() == null ?
                                        elements.get(++i).getText() :
                                        paperInformationFromFile.getOther().concat(" ").concat(elements.get(++i).getText()));
                        }
                    }
                }
            } else {
                ChapterEntity chapterEntity = new ChapterEntity();
//                List<DefaultElement> section = ((DefaultElement) element).elements("section");
//                StringBuilder stringBuilder = new StringBuilder();
//                for (int i = 0; i < section.size(); i++) {
//                    if (i != 0) {
//                        stringBuilder.append(" ");
//                    }
//                    List<DefaultElement> texts = section.get(i).elements("text");
//                    for (DefaultElement text : texts) {
//                        stringBuilder.append(" ").append(text.getText());
//                    }
//                }
                chapterEntity.setSubTitle(subTitle);
                chapterEntity.setContent(getStringFromSection((DefaultElement)element));
                chapterEntities.add(chapterEntity);
            }
        }
        paperInformationFromFile.setChapterEntities(chapterEntities);
        return paperInformationFromFile;
    }

    private String getStringFromSection(DefaultElement element) {
        List<DefaultElement> section = element.elements("section");
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < section.size(); i++) {
            if (i != 0) {
                stringBuilder.append(" ");
            }
            List<DefaultElement> texts = section.get(i).elements("text");
            for (DefaultElement text : texts) {
                stringBuilder.append(" ").append(text.getText());
            }
        }
        return stringBuilder.toString().replaceAll(" +", " ");
    }

    public List<String> getCitation(File file, String index) throws Exception{
        List<String> result = new ArrayList<>();
        Document document = new SAXReader().read(file);
        Element rootElement = document.getRootElement();
        Element content = rootElement.element("content");
        List<DefaultElement> elements = content.elements();
        for (DefaultElement element : elements) {
            String sectionString = getStringFromSection(element);
            if ("".equals(sectionString.trim())) {
                continue;
            }
            // 分句
            List<String> list = SplitTextInSentence.testChunkSentences(sectionString);
            List<DefaultElement> sections = element.elements("section");
            for (DefaultElement section : sections) {
                List<DefaultElement> textAndSup = section.elements();
                for (int i = 0; i < textAndSup.size(); i++) {
                    DefaultElement defaultElement = textAndSup.get(i);
                    if (defaultElement.getName().equals("sup") && defaultElement.getText().equals(index)) {
                        int j = i;
                        DefaultElement lastTextElement = textAndSup.get(j);
                        while (j >= 0 && ("sup".equals(lastTextElement.getName())
                                || "".equals(lastTextElement.getText().trim()))) {
                            j--;
                            lastTextElement = textAndSup.get(j);
                        }
                        if (j < 0) {
                            System.out.println("j<0");
                            continue;
                        }
                        String[] split = lastTextElement.getText().split("\\. ");
                        int k = split.length - 1;
                        List<String> matchSentence = null;
                        do {
                            matchSentence = new ArrayList<>();
                            StringBuilder sb = new StringBuilder();
                            for (int ii = k; ii < split.length; ii++) {
                                sb.append(split[ii]);
                            }
                            for (String s : list) {
                                if (s.trim().contains(sb.toString().trim())) {
                                    matchSentence.add(s);
                                    continue;
                                }
                            }
                            k--;
                        } while (matchSentence.size() != 1 && k >= 0);
                        if (matchSentence.size() == 1) {
                            result.add(matchSentence.get(0));
                        }
                    }
                }
            }
        }
        return result;
    }

    public static void main(String[] args) {
        final String path = "D:/paper_database/Lancet0324/S0140-6736(13)61207-6.xml";
        try {
//            PaperEntity paperEntityFromFile = new LancetXmlFileOperation().getPaperEntityFromFile(new File(path));
//            String title = paperEntityFromFile.getTitle();
            new LancetXmlFileOperation().getCitation(new File(path), "3");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
